const { request } = require('../../utils/request.js');
Component({
  properties: {
    isSearch: Boolean,
    emptyResult: Boolean,
    hasError: Boolean,
    errorMsg: String,
    keyword: String,
    results: Array,
    search_img: String
  },

  data: {
    posY: 48,               // 当前 Y 坐标
    imageHeight: 300,       // 顶部图片高度
    snapTop: 58,            // 吸附顶部位置
    snapBottom: 300,        // 吸附到底部位置（图片底部）
    isDragging: false,
    dragOffset: 0,          // 手指与容器顶部的距离
    startY: 0,              // 拖动起始位置
    isIndicatorTouched: false  // 是否按住指示条
  },

  lifetimes: {
    ready() {

    }
  },

  methods: {
    handleTouchStart(e) {
      // 如果按的是指示条
      const touchY = e.touches[0].clientY;
      const touchTarget = e.target.dataset.target;

      // 只有当触摸的是指示条时才允许拖动
      if (touchTarget === 'indicator') {
        this.setData({
          isDragging: true,
          dragOffset: touchY - this.data.posY,
          startY: touchY, // 记录初始 Y 值
          isIndicatorTouched: true
        });
      }
    },

    handleTouchMove(e) {
      if (!this.data.isDragging) return;

      const touchY = e.touches[0].clientY;
      const { snapTop, snapBottom, dragOffset } = this.data;
      let newY = touchY - dragOffset;
    
      // 限制 newY 不能超过 snapTop 也不能超过 snapBottom
      newY = Math.min(Math.max(newY, snapTop), snapBottom);
    
      this.setData({ posY: newY });

      // 阻止默认行为，避免在按住指示条时页面的滚动
      e.preventDefault();
    },

    handleTouchEnd(e) {
      if (!this.data.isDragging) return;

      const endY = e.changedTouches[0].clientY;
      const { startY, snapTop, snapBottom } = this.data;
    
      const deltaY = endY - startY;
      const threshold = 30;
    
      let finalPos = this.data.posY;
    
      if (deltaY > threshold) {
        finalPos = snapBottom - 20;
      } else if (deltaY < -threshold) {
        finalPos = snapTop;
      } else {
        // 保持当前位置
        finalPos = this.data.posY;
      }
    
      this.setData({
        posY: finalPos,
        isDragging: false,
        isIndicatorTouched: false  // 结束拖动
      });
    },

    onFeedbackTap() {
      wx.showModal({
        title: '反馈错题',
        content: '确认要反馈此题目有误吗？',
        success: (res) => {
          if (res.confirm) {
            const { keyword, results } = this.properties
            const user_id = wx.getStorageSync('userId')
            request('/api/feedback', 'post', {
              'content': JSON.stringify({
                keyword: keyword,
                results: results
              }),
              'user_id': user_id
            })
            wx.showToast({
              title: '反馈成功，谢谢！',
              icon: 'success'
            });
          }
        }
      });
    },

    onPageScroll(e) {
      // 如果正在手动拖动，不处理 scroll 事件
      if (this.data.isDragging) return;
    
      const scrollTop = e.scrollTop;
      const posY = scrollTop >= 88 ? 88 : scrollTop;
    
      this.selectComponent('#searchResult').setData({
        posY
      });
    }
  }
});
